package com.sheep.pattern.constructor;

import java.lang.reflect.Type;

/**
 * 建造者模式
 * 当 isRef 为 true 的时候，arg 表示 String 类型的 refBeanId，type 不需要设置；
 * 当 isRef 为 false 的时候，arg、type 都需要设置。
 * 请根据这个需求，完善 ConstructorArg 类。
 *
 * @author wangze
 * @date 2021-01-13 16:31.
 * 正确的建造者模式
 **/
public class ConstructorArg2 {
	private boolean isRef;
	private Class type;
	private Object arg;

	// 设为私有
	private ConstructorArg2(Builder builder) {
		this.isRef = builder.isRef;
		this.type = builder.type;
		this.arg = builder.arg;
	}
	// 静态内部类实现

	public static class Builder {
		private boolean isRef;
		private Class type;
		private Object arg;

		public Builder() {

		}

		public ConstructorArg2 build() {
			if (isRef) {
				if (arg == null) {
					throw new NullPointerException("参数为空");
				}
				if (!(arg instanceof String)) {
					throw new RuntimeException("必须为string 参数");
				}
				return new ConstructorArg2(this);
			}
			if (type == null || arg == null) {
				throw new NullPointerException("参数为空");
			}
			return new ConstructorArg2(this);
		}


		public Builder setRef(boolean ref) {
			// 这边可以添加校验
			this.isRef = ref;
			return this;
		}

		public Builder setType(Class type) {
			this.type = type;
			return this;
		}

		public Builder setArg(Object arg) {
			this.arg = arg;
			return this;
		}
	}

	public static void main(String[] args) {
		new ConstructorArg2.Builder().setRef(true).setArg("builder").build();
	}
}
